package com.leilei.auth;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Import;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @author lei
 * @create 2022-06-15 07:59
 * @desc 权限校验自动装配配置类
 **/
@Configuration
@EnableConfigurationProperties(AuthProperties.class)
@ConditionalOnProperty(prefix = AuthProperties.MS_INTERCEPTOR, name = "enable", matchIfMissing = true)
public class AuthAutoConfiguration {
    private final AuthProperties authProperties;

    public AuthAutoConfiguration(AuthProperties authProperties) {
        this.authProperties = authProperties;
    }

    @Bean
    public RestTemplate authRestTemplate() {
        // 设置restTemplate编码为utf-8
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }

    @Bean
    @DependsOn({"authRestTemplate"})
    public AuthInterceptor buildAuthInterceptor(RestTemplate authRestTemplate) {
        return new AuthInterceptor(authProperties, authRestTemplate);
    }

}
